package com.example.zuul.filter;

import com.example.zuul.otherservice.Otherservice;
import com.example.zuul.return_data.Mall_Data;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

@Component
public class Mall_filter extends ZuulFilter {

    @Autowired
    Otherservice otherservice;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        //获取当前请求的上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        //获取当次被拦截的请求对象
        HttpServletRequest request = requestContext.getRequest();


        //如果发现请求是该路径，则表示为去认证中心进行登录和token的赋予，则不对该请求做任何操作
       // System.out.println(request.getRequestURI()+"=================");
        String regx = "^/user/g_[\\w]+";

        if (Pattern.matches(regx,request.getRequestURI())){

        } else {

           //获取所有Cookie数组
            Cookie[] cookies=request.getCookies();
          //是否携带token的标记
            boolean path=false;
            //保存token
            String token="";
            if(cookies!=null){
                for (Cookie cookie : cookies) {
                    if(cookie.getName().equals("token")){
                        path=true;
                        token=cookie.getValue();

                    }

                }
            }

            //如果该请求头存在token
            if (path){

                //鉴定 token
               Mall_Data res=otherservice.checkAcs(token);
                System.out.println(res.toString());
               //验证成功
               if((int)res.get("code")==200){
                return null;
               }else {
                   requestContext.setSendZuulResponse(false);
                   requestContext.setResponseStatusCode((int)res.get("code"));
                   requestContext.setResponseBody((String)res.get("data"));
                   requestContext.setResponseBody((String)res.get("error"));

               }
            } else {
                requestContext.setSendZuulResponse(false);
                requestContext.setResponseStatusCode(520);
                requestContext.setResponseBody("The current session is not logged in ,please login !");

            }

        }
        return null;
    }


}